package com.zhkc.iess.online.test01.config;

import com.zhkc.iess.online.test01.core.HJ212Codec;
import com.zhkc.iess.online.test01.handler.HJ212DataHandler;
import com.zhkc.iess.online.test01.handler.NettyServerHandler;
import com.zhkc.iess.online.test01.handler.ServerIdleStateHandler;
import com.zhkc.iess.online.test01.service.RemotingService;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.LineBasedFrameDecoder;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.ObjectProvider;

public class NettyServerInitializer extends ChannelInitializer<SocketChannel> {

    private RemotingService remotingService;
    private ObjectProvider<HJ212DataHandler> hj212DataHandler;

    public NettyServerInitializer(RemotingService remotingService, ObjectProvider<HJ212DataHandler> hj212DataHandler) {
        this.remotingService = remotingService;
        this.hj212DataHandler = hj212DataHandler;
    }

    @Override
    protected void initChannel(SocketChannel ch) {

        ChannelPipeline pipeline = ch.pipeline();

        //空闲检测
        pipeline.addLast(new ServerIdleStateHandler());
        // 添加自定义的ChannelInboundHandlerAdapter来处理业务逻辑

        //粘包/拆包处理
        pipeline.addLast(new LineBasedFrameDecoder(1024));

        // 添加一个字符串解码器，用于将接收到的ByteBuf转换成字符串
        // 这里假设使用的是UTF-8字符集
        pipeline.addLast("decoder", new StringDecoder(CharsetUtil.UTF_8));

        // 添加一个字符串编码器，用于将发送的字符串转换成ByteBuf
        // 这样服务器发送字符串时，客户端可以直接接收到字符串
        pipeline.addLast("encoder", new StringEncoder(CharsetUtil.UTF_8));

        pipeline.addLast(new LoggingHandler(LogLevel.WARN));

        pipeline.addLast(new HJ212Codec());

        // 添加自定义的ChannelInboundHandlerAdapter来处理业务逻辑
        pipeline.addLast("handler", new NettyServerHandler(remotingService, hj212DataHandler));
    }
}